<template>
  <div>
    <request-detail v-if="isCreativeStillRequest == 1" :request-detail-info="requestDetailInfo" :offerInfo="offerInfo"></request-detail>
    <div class="upload-body" :style="isCreativeStillRequest === 0?'margin-top: -1em':'margin-top: 2em'" v-loading="loading" element-loading-background="rgba(255, 255, 255, 0.6)" element-loading-text="保存中,请稍候">
      <el-form :model="form" :rules="isCreativeStillRequest === 1?rules:creativeRules" ref="form" label-width="150px">
        <el-row :gutter="20">
          <!-- <el-col :span="8">
            <el-form-item label="素材设计师" prop="designer">
              <el-select id="id-offer-componets-creativerequest-conmponents-realName"
                         v-model="form.designer" filterable size="mini" :multiple="isCreativeStillRequest === 0">
                <el-option v-for="(item,index) in designersList" :key="index" :label="item.realName"
                           :value="item.id" v-if="(isCreativeStillRequest === 0?item.roleAlias.includes('designer'):item.status == 1 && item.isDeleted == 0 && requestDetailInfo.designers != null &&
                            requestDetailInfo.designers.split(',').includes(item.id))/*不用包含设计师负责人和管理员，因为他们不做设计*/">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col :span="8">
            <el-form-item label="素材状态" prop="demandIsProd">
              <el-radio-group v-model="isCreativeStillRequest ===0?form.demandIsProd = 1:form.demandIsProd">
                <el-radio :label="1">成品素材</el-radio>
                <el-radio :label="0" @change="isRadio">制作中素材</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="制作用时" prop="makeTime">
              <el-input-number id="id-offer-componets-creativerequest-conmponents-hour" v-model="form.makeTime.hour" :controls="false" :min="0" style="width: 80px" :max="2400" size="small" :step-strictly="true"
                               @blur="() =>{if(!form.makeTime.minute)form.makeTime.minute = 0 ; if(!form.makeTime.hour)form.makeTime.hour = 0}"></el-input-number>小时
              <el-input-number id="id-offer-componets-creativerequest-conmponents-minute" v-model="form.makeTime.minute" :controls="false" :min="0" style="width: 80px" :max="59" size="small" :step-strictly="true"
                               @blur="() =>{if(!form.makeTime.hour)form.makeTime.hour = 0;if(!form.makeTime.minute)form.makeTime.minute = 0 ;}"></el-input-number>分钟
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <!-- <el-col :span="8">
            <el-form-item label="原创者" prop="originator">
              <el-select id="id-offer-componets-creativerequest-conmponents-originator" v-model="form.originator" filterable size="mini" multiple>
                <el-option v-for="(item,index) in originatorList" :key="index" :label="item.realName"
                           :value="item.id" v-if="(item.status == 1 && item.isDeleted == 0)">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col :span="8">
            <el-form-item label="关联被拒素材" prop="id">
              <el-select id="id-offer-componets-creativerequest-conmponents-id" size="mini" v-model="form.id" clearable>
                <el-option v-for="(item,index) in prodRejectedCreativeList" :key="index" :label="item.name"
                           :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col span="8" v-if="isCreativeStillRequest === 0">
            <el-form-item label="媒体" prop="platform">
              <el-select size="mini" v-model="form.platform">
                <el-option v-for="(item,index) in platformList" :key="index" :value="item.dictKey"
                           :label="item.dictValue">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="isCreativeStillRequest === 0">
          <el-col :span="7">
            <el-form-item label="版本" size="mini">
              <el-input disabled value="1.0"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="状态" size="mini">
              <el-select size="mini" v-model="creativeStatus" disabled>
                <el-option v-for="(item,index) in form.creativeStatus" :key="index" :value="item.value"
                           :label="item.label">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="padding: 0 0 100px 150px">
          <creative-upload-prod-obs :file-map="fileMap" :plug-in-unit="tagsLength" :limit="50"
                               ref="beeltesUpload"></creative-upload-prod-obs>
        </el-row>
        <el-row>
          <div v-for="(item,index) in fileMap" :key="index" class="product-upload">
            <div>
              <ul class="el-upload-list el-upload-list--picture-card">
                <li class="el-upload-list__item is-ready" style="height: 155px;width: 155px">
                        <span v-if="item.type === 'image' || item.type === 'video'">
                          <el-progress v-if="item.progress !== 100" type="circle"
                                       :percentage="item.progress"></el-progress>
                          <span v-if="item.url === '-1'">上传失败</span>
                          <img v-if="item.type === 'image' && item.progress === 100 && item.url !=='-1' "
                               class="el-upload-list__item-thumbnail creative" :src="item.url" alt="">
                          <video v-if="item.type  === 'video' && item.progress === 100 && item.url !=='-1' "
                                 class="el-upload-list__item-thumbnail creative" :src="item.url"></video>
                         <span class="el-upload-list__item-actions">
                            <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(item)"><i
                              class="el-icon-zoom-in"></i></span>
                            <span v-if="item.type  === 'video'" class="el-upload-list__item-preview"><i
                              class="el-icon-video-camera"></i></span>
                            <span v-if="item.type === 'image'" class="el-upload-list__item-preview"><i
                              class="el-icon-picture-outline"></i></span>
                            <span v-if="!disabled" class="el-upload-list__item-delete"
                                  @click="handleRemove(item)"><i
                              class="el-icon-delete"></i></span>
                          </span>
                        </span>
                </li>
              </ul>
            </div>
            <div style="width: 100%;margin-left: 1em">
              <el-row :gutter="20" style="display: flex">
                <el-col>本地文件名: {{ item.name }}</el-col>
                <el-col>上传人:{{ creator }}</el-col>
              </el-row>
              <el-row :gutter="20" style="margin-top: 10px;margin-left: 1em">
                <el-col :span="18">
                  <el-input id="id-offer-componets-creativerequest-conmponents-thought"
                            type="textarea"
                            autosize
                            placeholder="设计思路"
                            :autosize="{ minRows: 3 }"
                            v-if="eventSeq > 0"
                            v-model="item.thought"></el-input>
                </el-col>
                <el-col :span="6" v-if="index === 0">
                  <el-button id="id-offer-componets-creativerequest-conmponents-copyToOther"
                             type="primary" size="medium" plain  @click="copyToOther">批量应用</el-button>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="素材设计师" prop="designer">
                    <el-select id="id-offer-componets-creativerequest-conmponents-realName"
                              v-model="item.designer" filterable size="mini" :multiple="isCreativeStillRequest === 0" @change="changeDesigner(item.designer)">
                      <el-option v-for="(item,index) in designersList" :key="index" :label="item.realName"
                                :value="item.id" v-if="(isCreativeStillRequest === 0?item.roleAlias.includes('designer'):item.status == 1 && item.isDeleted == 0 && requestDetailInfo.designers != null &&
                                  requestDetailInfo.designers.split(',').includes(item.id))/*不用包含设计师负责人和管理员，因为他们不做设计*/">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="原创者" prop="originator">
                    <el-select id="id-offer-componets-creativerequest-conmponents-originator" v-model="item.originator" filterable size="mini" multiple>
                      <el-option v-for="(item,index) in originatorList" :key="index" :label="item.realName"
                                 :value="item.id" v-if="(item.status == 1 && item.isDeleted == 0)">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row style="display: flex;align-items: center" v-if="eventSeq > 0 && tagsList != null && tagsList.length > 0">
                <div style="margin-right: 1em">标签</div>
                <div style="display: flex;align-items: center;flex-wrap: wrap;">
                  <div v-for="(group,ind) in tagsList" :key="ind" style="margin-right: 10px">
                    <el-tag type="info" v-if="group.type === 'system'">{{ group.name }}</el-tag>
                    <el-select id="id-offer-componets-creativerequest-conmponents-getObjectCount"
                               size="mini" v-if="group.type !== 'system' && group.tags != null && group.tags.length > 0"
                               multiple v-model="item.data[ind]"
                               style="margin-bottom: 5px"
                               :placeholder="group.name">
                      <el-option-group
                        v-if="getObjectCount(group.tags,'flag',1) > 0"
                        :key="0"
                        style="color: green;"
                        label="生成命名标签">
                        <el-option v-for="(it) in group.tags" :key="it.name" :value="it.name" v-if="it.flag == 1"
                                   :label="it.name">
                        </el-option>
                      </el-option-group>
                      <el-option-group
                        v-if="getObjectCount(group.tags,'flag',0) > 0"
                        :key="1"
                        style="color: green;"
                        label="不生成命名标签">
                        <el-option v-for="(it) in group.tags" :key="it.name" :value="it.name" v-if="it.flag == 0"
                                   :label="it.name">
                        </el-option>
                      </el-option-group>
                    </el-select>
                  </div>
                </div>
              </el-row>
            </div>
          </div>
        </el-row>
        <div style="display: flex;justify-content: center;margin-top: 1em;margin-bottom: 1em">
          <el-button v-if="isCreativeStillRequest===1" id="id-offer-componets-creativerequest-conmponents-productcreative" type="primary" size="medium" @click="save">保存</el-button>
          <el-button v-else id="id-offer-componets-creativerequest-conmponents-productcreativebak" type="primary" size="medium" @click="handleSubmit">保存</el-button>
        </div>
      </el-form>
    </div>
    <!--素材详情弹窗-->
    <el-dialog :visible.sync="dialogVisible" :modal-append-to-body="false" top="0px;"
               :close-on-click-modal="false" :before-close="handleClose" :append-to-body="true" width="80%">
      <div style="display: flex;justify-content: center;align-items: center">
        <img v-show="dialogType === 'image'" :style="previewStyle()" :src="dialogImageUrl">
        <video v-show="dialogType === 'video'" :src="dialogImageUrl" ref="video" :style="previewStyle()"
               controls="controls"></video>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import requestDetail from "@/views/offer/components/creativeRequest-components/requestDetail";
import creativeUploadProdObs from "@/components/beetles-upload/creative_upload_prod_obs";
import {getOfferTags} from "@/api/offer/creative";
import {addProductTagsCreative} from "@/api/offer/creativerequest"
import {getAllUser} from "@/api/user";
import {add, update} from '@/api/offer/creative'
import {mapGetters} from "vuex";

export default {
  name: "productCreative",
  components: {
    requestDetail, creativeUploadProdObs
  },
  props: {
    isCreativeStillRequest: Object,
    requestDetailInfo: Object,
    offerInfo: Object,
    close: Function,
    platformList: Array,
  },
  data() {
    let validateMakeTime = (rule, value, callback) => {
      if((value.minute == undefined || value.hour == undefined) || (('' + value.minute).trim() == '' || ('' + value.hour).trim() == '') || (value.minute == 0 && value.hour == 0)) {
        return callback(new Error('请输入制作时间'))
      } else {
        return callback();
      }
    };
    return {
      creativeStatus: 0,
      title: '',
      loading: false,
      form: {
        originator: '',
        designer: '',
        demandIsProd: '',
        makeTime: {
          minute: 0,
          hour: 0,
        },
        creativeStatus: [
          {label:'等待提交',value: 0}
        ]
      },
      tagsLength: 0,
      uploadList: [],
      designersList: [],
      originatorList: [],
      fileMap: [],//obs上传素材列表
      offerList: [],
      modelTags: {
        groupDiv: '',
        tagDiv: '',
      },
      creator: '',
      tagsList: [],//当前offer下的标签组
      dialogVisible: false,//素材详情弹窗
      dialogImageUrl: '',//素材地址
      dialogType: '',//素材类型
      creativeRules: {
        designer: [{required: true, message: '请选择设计师', trigger: 'change'}],
        demandIsProd: [{required: true, message: '请选择素材状态', trigger: 'change'}],
        platform: [{required: true, message: '请选择媒体', trigger: 'change'}],
      },
      rules: {
        designer: [{required: true, message: '请选择设计师', trigger: 'change'}],
        demandIsProd: [{required: true, message: '请选择素材状态', trigger: 'change'}],
        makeTime: [{required: true,message:"请输入制作时间",trigger: "change",},{required: true,validator: validateMakeTime, trigger: 'change'}],
      },
      eventSeq: 1
    }
  },
  created() {
    //获取当前offer下的标签
    this.init();
  },
  computed: {
    ...mapGetters(["userInfo"]),
  },
  methods: {
    changeDesigner(val){
      this.form.designer=val
    },
    isRadio(){
      if (this.isCreativeStillRequest === 0){
        this.form.demandIsProd = 1
      }
    },
    handleSubmit() {
      let self = this;
      self.title = 'add';
      let files = this.verificationFiles()
      if (files === false)
        return
      if(!this.$refs.beeltesUpload.uploadCompleted()) {
        this.$message.warning('文件未上传完成');
        return;
      }
      self.$refs['form'].validate((valid) => {
        if (valid) {
          let submitForm = {
            designer: this.form.designer.join(','),
            version: 1.0,
            platform: self.form.platform,
            originator: self.form.originator.join(','),
            status: 0,
            offerId: self.requestDetailInfo.offerId,
            filesMap: files
          }
          if (self.title === 'add') {
            self.loading = true
            self.rowSave(submitForm)
            //新增
            //参数 submitForm , files , offerId
          } else {
            //编辑
            self.loading = true
            let originId = null;
            if (self.title === 'dup') {
              submitForm.id = null;
              originId = self.form.id;
            }
            self.rowUpdate(submitForm, originId)
            //参数 submitForm , files ,
          }
        }
      })
    },
    //校验华为云素材
    verificationFiles() {
      let files = this.fileMap
      if (files.length === 0) {
        this.$message({
          type: 'error',
          message: '请提供上传素材!'
        })
        return false
      }

      let complete = true // 完成度
      files.map(item => {
        if (item.progress !== 100) {
          complete = false
        }
      })

      if (!complete) {
        this.$message({
          type: 'error',
          message: '请等待素材上传完成!'
        })
        return false
      }
      let val = {}
      files.map(item => {
        val[item.name] = item.url
      })
      return val
    },
    rowSave(v) {
      add(v).then(res => {
        if (res.data.data) {
          this.$message.success('操作成功')
          this.loading = false
          this.handleClose()
        }
      }, error => {
        this.$message.error('操作失败')
        this.loading = false
        this.handleClose()
      })
    },
    rowUpdate(v, i) {
      v['originId'] = i
      update(v).then(res => {
        if (res.data.data) {
          this.$message.success('更新完成')
          this.loading = false
          this.handleClose()
        }
      }, error => {
        this.$message.error('更新失败')
        this.loading = false
        this.handleClose()
      })
    },
    //初始化
    init() {
      getOfferTags(this.requestDetailInfo.offerId).then(res => {
        // debugger
        if (res.data.data.tagsSnapshot === null){
          this.$message({
            type: "warning",
            message: '当前订单暂未配置标签模板'
          })
          return
        }
        this.modelTags = res.data.data;
        this.tagsList = res.data.data.tagsSnapshot
        this.tagsLength = this.tagsList.length
      })
      getAllUser({statusList: '0,1,2', isAll: true}).then(res => {
        this.designersList = res.data.data;
        console.log(this.designersList)
        this.originatorList = res.data.data;
      })
      this.creator = this.userInfo.nick_name
    },
    getObjectCount(list, propName, propVal) {
      let objCount = 0;
      if (list != null) {
        list.forEach(ele => {
          if (ele != null) {
            if (ele[propName] == propVal) {
              objCount++;
            }
          }
        });
      }
      return objCount;
    },
    //素材详细
    handlePictureCardPreview(v) {
      if (v.type === 'image') {
        this.dialogType = 'image'
      } else if (v.type === 'video') {
        this.dialogType = 'video'
      }
      this.dialogImageUrl = v.url;
      this.dialogVisible = true;
    },
    //关闭素材详情弹窗
    handleClose() {
      this.dialogVisible = false
      this.$refs.video.pause();
    },
    previewStyle() {
      let height = ((window.innerHeight < 300) ? 300 : (window.innerHeight - 160));
      return {
        maxWidth: '100%',
        maxHeight: height + 'px'
      };
    },
    //删除素材
    handleRemove(v) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log('确认')
        this.$refs.beeltesUpload.removeByUid(v.uid);
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        console.log('取消')

        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    copyToOtherEnable() {
      if(this.fileMap.length > 1) {
        if(this.fileMap[0].thought && this.fileMap[0].thought.trim() != '') {
          return true;
        }
        if(this.fileMap[0].data != null) {
          for(let d=0;d<this.fileMap[0].data.length;d++) {
            if(this.fileMap[0].data[d] != null && this.fileMap[0].data[d].length > 0) {
              return true;
            }
          }
        }
      }
      return false;
    },
    copyToOther() {
      let firstTags = this.fileMap[0];
      this.fileMap.map((item, index) => {
        if (index > 0) {
          if(firstTags.data != null) {
            for(let n=0;n<firstTags.data.length;n++) {
              if(firstTags.data[n] != null) {
                item.data[n] = [...firstTags.data[n]];
              }
            }
          }
          item.thought = firstTags.thought;
          item.designer=firstTags.designer;
          item.originator=firstTags.originator;
          console.log(item.thought)
          console.log(item.designer)
          console.log(item.originator)

        }
      })
      this.eventSeq ++;
    },
    //保存成品素材
    save() {

      if (this.fileMap == null || this.fileMap.length == 0) {
        this.$message.error("请选择要上传的素材文件");
        return;
      }
      if(!this.$refs.beeltesUpload.uploadCompleted()) {
        this.$message.error("素材文件尚未上传完成");
        return;
      }
      this.$refs.form.validate(valid => {
        if (valid) {
          let platform = '';
          if (this.requestDetailInfo.platform != null) {
            // platform = this.requestDetailInfo.platform.split(',')[0];
            platform=this.requestDetailInfo.platform;
          }
          let creativeInfoList = [];
          this.fileMap.forEach(one => {
            let my = one;
            let creativeTagsSnapshot = [];
            for (let t = 0; t < this.tagsList.length; t++) {
              let group = this.tagsList[t];
              if (group.type == 'system') {
                creativeTagsSnapshot.push(group);
              } else if (my.data[t] != null && my.data[t].length > 0) {
                let newGroup = {...group};
                newGroup.tags = [];
                group.tags.forEach(tag => {
                  if (my.data[t].includes(tag.name)) {
                    newGroup.tags.push(tag);
                  }
                });
                creativeTagsSnapshot.push(newGroup);
              }
            }
            creativeInfoList.push({
              fileMap: {
                name: one.name,
                url: one.url,
                type: one.type,
                creator: this.creator
              },
              thought: my.thought,
              designer: one.designer,
              originator:one.originator.join(','),
              // designer:this.fileMap[0].designer,
              // originator:this.fileMap[0].originator[0].toString(),

              groupDiv: this.modelTags.groupDiv,
              tagDiv: this.modelTags.tagDiv,
              tagsSnapshot: JSON.stringify(creativeTagsSnapshot),
            });
          });
          // let index=this.fileMap.length
          // let designerArr=[]
          // let originatorArr=[]
          // for(let i=0;i<index;i++){
          //   designerArr.push(this.fileMap[i].designer)
          //   for(let j=0;j<this.fileMap[i].originator.length;j++){
          //     originatorArr.push(this.fileMap[i].originator[j])
          //   }
          // }
          let baseCreative = {
            tags: '',
            // originator: this.form.originator.join(','),
            // 成功
            // originator:this.fileMap[0].originator[0].toString(),
            demandIsProd: this.form.demandIsProd,
            makeTime: (this.form.makeTime.minute * 60 + this.form.makeTime.hour * 3600),
            offerId: this.requestDetailInfo.offerId,
            platform: platform,

            //成功
            // designer: this.fileMap[0].designer,
            status: '0',
            demandStatus: '1',   //0：未上传 1：设计师上传的成品素材； 2：优化师通过； 3： 优化师拒绝
            ownedDemandId: this.requestDetailInfo.id,
            creativeInfoList: creativeInfoList,
          };
          if(this.loading) {
            return;
          }
          this.loading = true
          addProductTagsCreative(baseCreative).then(res => {
            if (res.data.success) {
              this.$message({
                type: 'success',
                message: '保存成功!'
              });
              if (this.close) {
                this.close();
              }
            }
          }, error => {
          }).finally(() => {
            this.loading = false
          })
        }
      });
      console.log(this.fileMap)
    }
  }
}
</script>

<style scoped lang="scss">
.upload-body {
  width: 100%;
  background-color: rgba(245, 245, 245, 100);
  border: 1px solid rgba(232, 232, 232, 100);
  border-radius: 10px;
  margin-top: 2em;
  padding-top: 1em;
}

.hide .el-upload--picture-card {
  display: none;
}

// 添加/删除文件时去掉动画过渡
.el-upload-list__item {
  transition: none !important;
}

.el-upload-list--picture-card {
  display: block;
}

.upload-error {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center
}

.product-upload {
  display: flex;
  margin-left: 150px;
  margin-top: 20px
}

/deep/ .el-select-group__title {
  background: #e9e9e9;
}
</style>
